// 定义学生信息结构
class StudentInfo {
    id: u32;
    name: string;
    age: u32;
    grade: u32;
    time: f64; // 添加时间属性
    vars: f64[]; // f64类型数组，长度1000

    constructor(id: u32, name: string, age: u32, grade: u32, time: f64, vars: f64[]) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.grade = grade;
        this.time = time;
        this.vars = vars;
    }

    // 将学生信息写入内存，确保内存对齐以适配f64数组写入
    static writeMemory(ptr: usize, student: StudentInfo): void {
        store<u32>(ptr, student.id);
        store<u32>(ptr + 4, student.age);
        store<u32>(ptr + 8, student.grade);
        store<f64>(ptr + 16, student.time); // 存储时间，16 是 8 的倍数
        const namePtr = ptr + 24;
        const nameLength = student.name.length;
        for (let i = 0; i < nameLength; i++) {
            store<u8>(namePtr + i, student.name.charCodeAt(i));
        }
        store<u8>(namePtr + nameLength, 0); // 终止符

        // 计算并调整到8字节对齐的偏移量，用于f64数组写入
        let varsPtr = ptr + 24 + nameLength + 1;
        const offsetToAlign = (8 - ((varsPtr) % 8)) % 8;
        varsPtr += offsetToAlign;

        for (let i = 0; i < 1000; i++) {
            store<f64>(varsPtr + i * 8, student.vars[i]); // 每个f64元素占8字节
        }
    }

    // 从内存读取学生信息，同样确保内存对齐来读取f64数组
    static readMemory(ptr: usize): StudentInfo {
        const id = load<u32>(ptr);
        const age = load<u32>(ptr + 4);
        const grade = load<u32>(ptr + 8);
        const time = load<f64>(ptr + 16); // 读取时间，16 是 8 的倍数
        const namePtr = ptr + 24;
        let name = "";
        let i = 0;
        while (true) {
            const charCode = load<u8>(namePtr + i);
            if (charCode === 0) break;
            name += String.fromCharCode(charCode);
            i++;
        }

        // 计算并调整到8字节对齐的偏移量，用于f64数组读取
        let varsPtr = ptr + 24 + i + 1;
        const offsetToAlign = (8 - ((varsPtr) % 8)) % 8;
        varsPtr += offsetToAlign;

        const vars = new Array<f64>(1000);
        for (let j = 0; j < 1000; j++) {
            vars[j] = load<f64>(varsPtr + j * 8); // 读取每个f64元素
        }

        return new StudentInfo(id, name, age, grade, time, vars);
    }
}

// 导出函数 withInputAndOutput
export function withInputAndOutput(inputStudentPtr: usize): usize {
    // 从内存中读取传入的学生信息
    const startTime1 = performance.now();
    const inputStudent = StudentInfo.readMemory(inputStudentPtr);
    const endTime1 = performance.now();
    const inputTime = endTime1 - startTime1;

    // 修改学生的 id
    inputStudent.id += 1;

    // 设置时间属性
    inputStudent.time = inputTime;

    // 将修改后的学生信息写回内存
    StudentInfo.writeMemory(inputStudentPtr, inputStudent);

    // 返回学生信息的指针
    return inputStudentPtr;
}